import { Checkbox, Col, Row, Space, message } from 'antd';
import React, { useState, useImperativeHandle, useEffect } from 'react';
import { IconC, SecondHeaderC, ThreeHeaderC, SceneCardC } from '@/src/components';
import { sceneTree, sceneToRisk, riskToScene } from '../constantConfig';
import styles from './index.less';
import { useSelector } from 'umi';
import { cloneDeep } from 'lodash';
import { operateTypeObj, namespace } from '@/src/newModels/pressureReport/SceneTemplateSettingsM';
import {
  deleteStringsFromArray,
  checkedAndDisabledRollback,
  filterExistItem,
  insertRiskFactor,
  filterAndSortTreeData,
  transCheckedAndDisabled,
  sortInfo,
  extractLastLevelIds,
} from './disposeDataFn';

const sceneTreeWithRiskFactor = insertRiskFactor(sceneTree, sceneToRisk);
const StepTwo = (props) => {
  const modelStateInfo = useSelector((state) => state[namespace]);
  const [toRightStatus, setToRightStatus] = useState(false); //
  const [sceneIdListLeft, setSceneIdListLeft] = useState([]); // 左侧情景id数组
  const [checkListLeft, setCheckListLeft] = useState(cloneDeep(sceneTreeWithRiskFactor)); // 左侧情景渲染列表数组
  const [sceneIdListRight, setSceneIdListRight] = useState([]); // 右侧情景id数组
  const [checkListRight, setCheckListRight] = useState([]); // 右侧情景渲染列表数组
  const {
    operateType,
    mainState: { sceneTemplateInfo },
    copiedSceneTemplateInfo,
  } = modelStateInfo;

  // 给编辑和复制模板用来设置第二部选择情景的数据
  const reRenderSceneItem = (sceneList) => {
    // 设置选中的和禁用的（已穿梭到右边的）
    const res = transCheckedAndDisabled(checkListLeft, sceneList, true);
    setSceneIdListLeft(sceneList); // 1.设置左侧选中的情景
    setCheckListLeft(res); // 2.设置左侧禁用的
    // 3.设置右侧根据左侧生成的
    const sceneTreeWithRiskFactorCopy = cloneDeep(sceneTreeWithRiskFactor);
    const sceneTreeWithRiskFactorRight = filterAndSortTreeData(sceneTreeWithRiskFactorCopy, sceneList); // 通过选中的左边的找到右边符合的
    setCheckListRight(sceneTreeWithRiskFactorRight); // 设置找到的右侧数据
  };
  useEffect(() => {
    // 如果新增而且选择了复制
    if (operateType === operateTypeObj.add) {
      if (copiedSceneTemplateInfo) {
        const { sceneList } = copiedSceneTemplateInfo;
        reRenderSceneItem(sceneList);
      }
    } else {
      // 是编辑，取首页的详情数据
      handleEdit();
    }
  }, [copiedSceneTemplateInfo]);
  const handleEdit = () => {
    // 步骤二，监听current ，优化re-render
    if (operateType === operateTypeObj.edit) {
      if (sceneTemplateInfo) {
        const { sceneList } = sceneTemplateInfo;
        reRenderSceneItem(sceneList);
      }
    }
  };

  const getSelectedSceneInfo = () => {
    return new Promise((resolve, reject) => {
      if (checkListRight.length === 0) {
        message.info('请先选择情景项！');
        reject('已选情景项不能为空');
      }
      resolve({
        sceneInfo: checkListRight,
        sceneIdInfo: extractLastLevelIds(checkListRight, 'id'),
      });
    });
  };
  useImperativeHandle(props.onRef, () => ({
    getSelectedSceneInfo,
  }));
  // 左侧选择情景节点
  const chooseItemLeft = (checkedValues) => {
    const disabledIds = extractLastLevelIds(checkListLeft, 'id', true); // 左侧所有禁用的ids
    setToRightStatus(checkedValues.length !== disabledIds.length); // 不相等则高亮
    setSceneIdListLeft(checkedValues);
    const res = transCheckedAndDisabled(checkListLeft, checkedValues, false);
    setCheckListLeft(res); // 设置左侧受控状态
  };
  // 右侧选择情景节点
  const chooseItemRight = (checkedValues) => {
    setSceneIdListRight(checkedValues);
    console.log('chooseItemRight', checkedValues);
    const res = transCheckedAndDisabled(checkListRight, checkedValues, false);
    setCheckListRight(res); // 设置右侧受控状态
  };
  // 穿梭操作
  const transDirect = (transType) => {
    // 从左往右穿梭
    if (transType === 'right') {
      setToRightStatus(false);
      const res = transCheckedAndDisabled(checkListLeft, sceneIdListLeft, true); // 找到左侧已经选择的来设置禁用
      setCheckListLeft(res); // 设置左侧已经穿梭到右边的禁用项
      const sceneTreeWithRiskFactorCopy = cloneDeep(sceneTreeWithRiskFactor);
      const sceneTreeWithRiskFactorRight = filterAndSortTreeData(sceneTreeWithRiskFactorCopy, sceneIdListLeft); // 通过选中的左边的找到右边符合的
      setCheckListRight(sceneTreeWithRiskFactorRight); // 设置找到的右侧数据
    }
    // 从右往左穿梭
    if (transType === 'left') {
      // 1 右侧选择的节点sceneIdListRight 删除选中的removeEmptyChildren
      const res = filterExistItem(checkListRight, sceneIdListRight);
      setCheckListRight(res);
      setSceneIdListRight([]); // 重置右侧选中的
      // 2 右侧选择的节点sceneIdListRight 找到左侧的渲染数据放开禁用, 受控checked不生效<Checkbox.Group/>使用value受控
      const leftRes = checkedAndDisabledRollback(checkListLeft, sceneIdListRight);
      setCheckListLeft(leftRes); // 设置左侧disabled
      const leftCheckedList = deleteStringsFromArray(sceneIdListLeft, sceneIdListRight); // 根据右侧的选中状态删除取消左侧的选中
      setSceneIdListLeft(leftCheckedList); // 设置左侧受控选中状态
    }
  };
  // 上移下移处理
  const moveChange = (type, id) => {
    const checkListRightCopy = cloneDeep(checkListRight);
    const res = sortInfo(checkListRightCopy, id, type);
    console.log(res, id);
    setCheckListRight(res);
  };
  return (
    <div className={styles.StepTwo}>
      <div className={styles.left}>
        <div className={styles.leftHeader}>待选情景项</div>
        <div className={styles.leftScroll}>
          <Checkbox.Group onChange={chooseItemLeft} value={sceneIdListLeft}>
            {checkListLeft.map((v) => {
              return (
                <div key={v.id}>
                  <SecondHeaderC title={v.name} />
                  <div style={{ marginBottom: 16, paddingLeft: 20 }}>
                    {v.children.map((item, index) => {
                      if (!item.children) {
                        return (
                          <Row key={item?.id}>
                            <Col span={24}>
                              <Checkbox disabled={item?.disabled} checked={item?.checked} value={item?.id}>
                                {item?.name}
                              </Checkbox>
                            </Col>
                          </Row>
                        );
                      } else {
                        return (
                          <>
                            <ThreeHeaderC title={item.name} style={{ marginLeft: -20 }} />
                            <div style={{ marginBottom: 16 }}>
                              {item.children.map((threeItem) => {
                                return (
                                  <Row key={threeItem?.id}>
                                    <Col span={24}>
                                      <Checkbox disabled={threeItem?.disabled} checked={true} value={threeItem?.id}>
                                        {threeItem?.name}
                                      </Checkbox>
                                    </Col>
                                  </Row>
                                );
                              })}
                            </div>
                          </>
                        );
                      }
                    })}
                  </div>
                </div>
              );
            })}
          </Checkbox.Group>
        </div>
      </div>
      <div className={styles.middle}>
        <Space direction='vertical' style={{ display: 'flex' }}>
          <IconC isDisabled={!toRightStatus} type={'rightArrow'} style={{ width: 24, height: 24 }} onClick={() => transDirect('right')} />
          <IconC isDisabled={!(sceneIdListRight.length > 0)} type={'leftArrow'} style={{ width: 24, height: 24 }} onClick={() => transDirect('left')} />
        </Space>
      </div>
      <div className={styles.right}>
        <div className={styles.rightHeader}>
          <span>已选情景项</span>
          <span className={styles.rightHeaderRightText}>因子与情景关联性分析</span>
        </div>
        <div className={styles.rightScroll}>
          <Checkbox.Group onChange={chooseItemRight} value={sceneIdListRight}>
            {checkListRight.map((v, idx) => {
              return (
                <div key={v.id}>
                  <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                    <SecondHeaderC title={v.name} />
                    <Space style={{ display: 'flex', paddingRight: 18 }}>
                      <IconC
                        isDisabled={idx === 0}
                        type={'threeArrowsDown'}
                        style={{ width: 14, height: 14, transform: 'rotate(180deg)' }}
                        onClick={() => moveChange('up', v.id)}
                      />
                      <IconC isDisabled={idx === checkListRight.length - 1} type={'threeArrowsDown'} style={{ width: 14, height: 14 }} onClick={() => moveChange('down', v.id)} />
                    </Space>
                  </div>
                  <div style={{ marginBottom: 16, padding: '0 20px' }}>
                    {v.children.map((item, index) => {
                      if (!item.children) {
                        return (
                          <SceneCardC
                            isContainCheckGroup={true}
                            style={{ marginBottom: 16 }}
                            showChecked={true}
                            title={item?.name}
                            upDisabled={index === 0}
                            downDisbled={index === v.children.length - 1}
                            showMove={true}
                            moveChange={moveChange}
                            id={item?.id}
                            key={item?.id}
                            content={
                              <div className={styles.sceneDes}>
                                {item.riskFactor.map((riskFactorItem) => {
                                  const tipInfo = riskToScene.find((riskItem) => riskFactorItem.id === riskItem.riskId);
                                  return (
                                    <div className={styles.line} key={riskFactorItem.name}>
                                      {riskFactorItem.name}
                                      {riskFactorItem?.remark ? `（${riskFactorItem?.remark}）` : null}
                                      <IconC
                                        title={
                                          <div>
                                            {tipInfo?.scene?.map((v) => {
                                              return <div key={v.path}>{v.path}</div>;
                                            })}
                                          </div>
                                        }
                                        style={{ marginTop: -3, marginLeft: 8 }}
                                        type={'illustrate'}
                                      />
                                    </div>
                                  );
                                })}
                              </div>
                            }
                          />
                        );
                      } else {
                        return (
                          <>
                            <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                              <ThreeHeaderC title={item.name} style={{ marginLeft: -20 }} />
                              <Space style={{ display: 'flex', paddingRight: 10 }}>
                                <IconC
                                  isDisabled={index === 0}
                                  type={'doubleDownArrow'}
                                  style={{ width: 12, height: 12, transform: 'rotate(180deg)' }}
                                  onClick={() => moveChange('up', item.id)}
                                />
                                <IconC
                                  isDisabled={index === v.children.length - 1}
                                  type={'doubleDownArrow'}
                                  style={{ width: 12, height: 12 }}
                                  onClick={() => moveChange('down', item.id)}
                                />
                              </Space>
                            </div>
                            <div style={{ marginBottom: 16 }}>
                              {item.children.map((threeItem, threeIdx) => {
                                return (
                                  <SceneCardC
                                    isContainCheckGroup={true}
                                    style={{ marginBottom: 16 }}
                                    showChecked={true}
                                    title={threeItem?.name}
                                    upDisabled={threeIdx === 0}
                                    downDisbled={threeIdx === item.children.length - 1}
                                    showMove={true}
                                    moveChange={moveChange}
                                    id={threeItem?.id}
                                    key={threeItem?.id}
                                    content={
                                      <div className={styles.sceneDes}>
                                        {threeItem.riskFactor.map((riskFactorItem) => {
                                          const tipInfo = riskToScene.find((riskItem) => riskFactorItem.id === riskItem.riskId);
                                          return (
                                            <div className={styles.line} key={riskFactorItem.name}>
                                              {riskFactorItem.name}
                                              {riskFactorItem?.remark ? `（${riskFactorItem?.remark}）` : null}
                                              <IconC
                                                title={
                                                  <div>
                                                    {tipInfo?.scene?.map((v) => {
                                                      return <div key={v.path}>{v.path}</div>;
                                                    })}
                                                  </div>
                                                }
                                                style={{ marginTop: -3, marginLeft: 8 }}
                                                type={'illustrate'}
                                              />
                                            </div>
                                          );
                                        })}
                                      </div>
                                    }
                                  />
                                );
                              })}
                            </div>
                          </>
                        );
                      }
                    })}
                  </div>
                </div>
              );
            })}
          </Checkbox.Group>
        </div>
      </div>
    </div>
  );
};
export default StepTwo;
